package uk.ac.ebi.pride.tools.pap.rest;

import org.apache.log4j.Logger;
import uk.ac.ebi.pride.tools.pap.AccessionProvider;
import uk.ac.ebi.pride.tools.pap.AccessionProviderException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Florian Reisinger
 *         Date: 19-Feb-2009
 * @since 0.1
 */
public class DefaultRestHandler {

    private static final Logger log = Logger.getLogger(DefaultRestHandler.class);

    private static final AccessionProvider AC_PROV = new AccessionProvider();

    public static void executeRequest(HttpServletRequest request, HttpServletResponse response, AccessionProvider.AcCase useCase) throws ServletException, IOException {
        log.info("REST request for PRIDE " + useCase.getName() + " accessions.");
        String countParam = request.getParameter("count");
        log.debug("Request 'count' parameter for URL '" + request.getRequestURI() + "': " + countParam);
        if (countParam != null) {
            int count;
            try {
                count = Integer.parseInt(countParam);
            } catch (Exception e) {
                throw new ServletException("Provided value for parameter 'count' could not be parsed into an int!", e);
            }

            List<String> resultLines = new ArrayList<String>();
            if (count > 0) {
                try {
                    List<Long> accessions = AC_PROV.getAccessions(count, useCase);
                    if (accessions != null) {
                        resultLines.add("PRIDE " + useCase.getName() + " accession");
                        for (Long accession : accessions) {
                            resultLines.add(accession.toString());
                        }
                    }
                } catch (AccessionProviderException e) {
                    log.error("Exception trying to run REST service.", e);
                    resultLines.add("Exception during service execution:");
                    resultLines.add(e.getMessage());
                }
            }


            PrintWriter responseWriter = response.getWriter();
            for (String line : resultLines) {
                responseWriter.println(line);
            }
            responseWriter.flush();
            responseWriter.close();

        } else {
            log.error("Could not find required parameter 'count' in request URL: " + request.getRequestURI());
            throw new ServletException("Required parameter 'count' missing!");
        }
    }

}
